﻿using System.Linq;
using System.Security.Principal;
using System.Web;
using XRM.Security.DataAccess.Repositories.Impl;

namespace XRM.Security.WebUI.Security
{
    public class UserPrincipal : IPrincipal, IIdentity
    {
        public int UserId { get; set; }
        public string DisplayName { get; set; }

        public static UserPrincipal Current
        {
            get
            {
                var httpContext = HttpContext.Current;
                if ( httpContext == null )
                {
                    return null;
                }
                return httpContext.User as UserPrincipal;
            }
        }

        public string[] Roles
        {
            get
            {
                using ( var roleMemberRepository = new RoleMemberRepository() )
                {
                    return roleMemberRepository.GetRolesByUserId( UserId ).Select( s => s.Name ).ToArray();
                }
            }
        }

        public bool IsInRole(string role)
        {
            using(var roleMemberRepository = new RoleMemberRepository())
            {
                return roleMemberRepository.UserInRole( UserId, role );
            }
        }

        public IIdentity Identity { get { return this; } }

        public string Name { get; set; }

        public string AuthenticationType { get; set; }

        public bool IsAuthenticated { get; set; }
    }
}